﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using MediaLibraryManagement.BLL;
using MediaLibraryManagement.Common;
using MediaLibraryManagement.Entity;

namespace MediaLibraryManagement.UI
{
    public partial class MovieDetails : Form
    {
        private Movie _movie;
        private float _rating;
        private int _ratingCount;

        public MovieDetails()
        {
            InitializeComponent();
            dgvCasting.AutoGenerateColumns = false;
        }

        public MovieDetails(Movie movie)
        {
            InitializeComponent();
            _movie = movie;
            dgvCasting.AutoGenerateColumns = false;
        }

        private void MovieDetails_Load(object sender, EventArgs e)
        {
            if (_movie != null)
            {
                txtTitle.Text = _movie.Title;
                txtGenre.Text = _movie.Genre;
                spnLength.Value = _movie.Length;
                dtpReleaseDate.Value = _movie.ReleaseDate;
                txtDirector.Text = _movie.Director;
                txtScriptWriters.Text = _movie.ScriptWriters;
                txtProductionCompany.Text = _movie.ProductionCompany;
                txtLanguage.Text = _movie.Language;
                txtImdb.Text = _movie.IMDB;
                txtStoryline.Text = _movie.Storyline;
                picMovieImage.Image = _movie.Image;
                _rating = _movie.Rate;
                _ratingCount = _movie.RatingCount;
                lblRatingNumber.Text = Math.Round(_rating, 2) + "/10";
                dgvCasting.DataSource = _movie.Casting;
                if (GlobalObjects.CurrentUser != null)
                {
                    if (GlobalObjects.CurrentUser.Privilege != Privileges.Viewer)
                    {
                        SetReadOnly(false);
                    }
                    else
                    {
                        SetReadOnly(true);
                    }
                    btnSave.Visible = true;
                }
                else
                {
                    SetReadOnly(true);
                    cboRating.Enabled = false;
                    btnSave.Visible = false;
                }
            }
            else
            {
                _rating = 0;
                _ratingCount = 0;
            }
        }

        #region Private Methods

        private void SetReadOnly(bool isReadOnly)
        {
            txtTitle.ReadOnly = isReadOnly;
            txtGenre.ReadOnly = isReadOnly;
            spnLength.Enabled = !isReadOnly;
            dtpReleaseDate.Enabled = !isReadOnly;
            txtDirector.ReadOnly = isReadOnly;
            txtScriptWriters.ReadOnly = isReadOnly;
            txtProductionCompany.ReadOnly = isReadOnly;
            txtLanguage.ReadOnly = isReadOnly;
            txtImdb.ReadOnly = isReadOnly;
            txtStoryline.ReadOnly = isReadOnly;
            dgvCasting.ReadOnly = isReadOnly;
            btnBrowseImage.Enabled = !isReadOnly;
        }

        #endregion

        private void btnBrowseImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlgOpenFile = new OpenFileDialog();
            dlgOpenFile.Filter = GlobalObjects.ImageFilter;
            dlgOpenFile.Multiselect = false;
            if (dlgOpenFile.ShowDialog() == DialogResult.OK)
            {
                Image image = Image.FromFile(dlgOpenFile.FileName);
                Image newImage = Utilities.ScaleImage(image, picMovieImage.Width, picMovieImage.Height);
                picMovieImage.Image = newImage;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            MovieBLL business = new MovieBLL();
            Movie movie = new Movie();
            movie.Title = txtTitle.Text.Trim();
            movie.Genre = txtGenre.Text.Trim();
            movie.Length = (int)spnLength.Value;
            movie.ReleaseDate = dtpReleaseDate.Value;
            movie.Director = txtDirector.Text.Trim();
            movie.ScriptWriters = txtScriptWriters.Text.Trim();
            movie.ProductionCompany = txtProductionCompany.Text.Trim();
            movie.Language = txtLanguage.Text.Trim();
            movie.IMDB = txtImdb.Text.Trim();
            movie.Storyline = txtStoryline.Text.Trim();
            movie.Image = picMovieImage.Image;
            List<Cast> casts = new List<Cast>();
            foreach (DataGridViewRow row in dgvCasting.Rows)
            {
                if (dgvCasting.Rows.IndexOf(row) != dgvCasting.Rows.Count - 1)
                {
                    Cast cast = new Cast();
                    cast.Artist = row.Cells["Cast_ArtistName"].Value.ToString().Trim();
                    cast.Role = row.Cells["Cast_Role"].Value.ToString().Trim();
                    casts.Add(cast);
                }
            }
            movie.Casting = casts;
            if (cboRating.SelectedIndex > 0)
            {
                int selectedRate = (int)cboRating.SelectedIndex;
                _rating = (float)(_rating * _ratingCount + selectedRate) / (_ratingCount + 1);
                _ratingCount++;
            }
            movie.Rate = _rating;
            movie.RatingCount = _ratingCount;
            try
            {
                if (_movie == null)
                {
                    business.Insert(movie);
                    MessageBox.Show("Thêm phim mới thành công.");
                    this.Close();
                }
                else
                {
                    movie.ID = _movie.ID;
                    business.Update(movie);
                    MessageBox.Show("Cập nhật phim thành công.");
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi hệ thống:\n" + ex, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void lnkViewProfileURL_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(txtImdb.Text))
            {
                ProcessStartInfo startInfo = new ProcessStartInfo(txtImdb.Text);
                Process.Start(startInfo);
            }
        }
    }
}